package com.blog.service.impl;

import com.alibaba.fastjson.JSON;
import com.blog.mapper.SearchMapper;
import com.blog.pojo.Article;
import com.blog.pojo.ArticleEs;
import com.blog.service.IndexService;
import org.apache.dubbo.config.annotation.DubboService;
import org.elasticsearch.index.query.MatchAllQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;

import org.springframework.data.elasticsearch.core.ElasticsearchTemplate;
import org.springframework.data.elasticsearch.core.query.NativeSearchQuery;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;

import java.util.ArrayList;
import java.util.List;
@DubboService
public class IndexServiceImpl implements IndexService {
    @Autowired
    private SearchMapper searchMapper;

    @Override
    public List<Article> pageArticles(int offset, int limit) {
        NativeSearchQuery query = new NativeSearchQueryBuilder().withPageable(PageRequest.of(offset-1, limit)).build();
        Page<ArticleEs> search = searchMapper.search(query);
        ArrayList<Article> list = new ArrayList<>();
        for (ArticleEs articleEs : search) {
            String jsonString = JSON.toJSONString(articleEs);
            Article article = JSON.parseObject(jsonString, Article.class);
            list.add(article);
        }

        return list;
    }

    @Override
    public long count() {
        return searchMapper.count();
    }
}
